<template>
  <div class="ad-details-container">
    <el-page-header @back="$router.go(-1)" content="广告详情" />
    
    <el-card v-loading="loading" class="details-card">
      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="2" border>
        <el-descriptions-item label="广告ID">{{ adData.id }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(adData.status)">
            {{ statusMap[adData.status] }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="广告标题">{{ adData.title }}</el-descriptions-item>
        <el-descriptions-item label="广告类型">
          {{ typeOptions[adData.type] || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="预算金额">¥{{ adData.budget?.toFixed(2) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 广告内容 -->
      <div class="content-section">
        <h4>广告内容</h4>
        <div class="content-box">{{ adData.content }}</div>
      </div>

      <!-- 广告媒体 -->
      <div class="media-section">
        <h4>广告媒体</h4>
        <div class="media-content">
          <!-- 图片广告 -->
          <div v-if="adData.type === 1 || adData.type === 2" class="image-container">
            <el-image 
              :src="adData.advertising" 
              fit="contain"
              :preview-src-list="[adData.advertising]"
              class="ad-image"
            />
          </div>
          
          <!-- 视频广告 -->
          <div v-else-if="adData.type === 3" class="video-container">
            <video 
              class="ad-video" 
              controls
              :src="adData.advertising"
            >
              您的浏览器不支持视频播放
            </video>
          </div>
          
          <div v-else class="no-media">
            无媒体内容
          </div>
        </div>
      </div>
      
      <!-- 时间信息 -->
      <el-descriptions title="时间信息" :column="2" border class="time-section">
        <el-descriptions-item label="创建时间">{{ formatTime(adData.createdTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatTime(adData.updatedTime) }}</el-descriptions-item>
        <el-descriptions-item label="投放开始">{{ formatTime(adData.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="投放结束">{{ formatTime(adData.endTime) }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 排期信息 -->
      <div class="schedule-section">
        <h4>排期信息</h4>
        <div v-loading="scheduleLoading">
          <el-table
            v-if="scheduleData.length > 0"
            :data="scheduleData"
            stripe
            border
            style="width: 100%"
            class="schedule-table"
          >
            <el-table-column prop="id" label="排期ID" width="80" />
            <el-table-column prop="deviceName" label="设备名称" />
            <el-table-column label="投放时间" width="280">
              <template #default="scope">
                {{ formatTime(scope.row.startTime) }} 至 {{ formatTime(scope.row.endTime) }}
              </template>
            </el-table-column>
            <el-table-column label="时间段" width="220">
              <template #default="scope">
                <div v-if="scope.row.timeSlots && scope.row.timeSlots.length > 0">
                  <div v-for="(slot, index) in scope.row.timeSlots" :key="index">
                    {{ slot.startTime }} - {{ slot.endTime }}
                  </div>
                </div>
                <span v-else>全天</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getScheduleStatusType(scope.row.status)">
                  {{ scheduleStatusMap[scope.row.status] || scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="效果数据" width="180">
              <template #default="scope">
                <div>展示: {{ scope.row.impressions || 0 }}</div>
                <div>点击: {{ scope.row.clicks || 0 }}</div>
              </template>
            </el-table-column>
          </el-table>
          
          <el-empty v-else-if="!scheduleLoading" description="暂无排期数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAdvertisementDetail } from '@/api/advertisement'
import { getAdvertisementSchedule } from '@/api/schedule'
import dayjs from 'dayjs'

const route = useRoute()
const loading = ref(false)
const adData = ref({
  id: null,
  title: '',
  content: '',
  status: 0,
  budget: 0,
  type: 1, // 默认为文字广告
  advertising: '', // 广告媒体URL
  startTime: null,
  endTime: null,
  createdTime: null,
  updatedTime: null
})

// 排期相关数据
const scheduleLoading = ref(false)
const scheduleData = ref([])
const deviceNames = ref({}) // 用于存储设备ID到设备名称的映射

// 广告类型选项
const typeOptions = {
  1: '文字广告',
  2: '图片广告',
  3: '视频广告',
}

// 状态映射
const statusMap = {
  0: '待审核',
  1: '已审核',
  2: '投放中',
  3: '已完成',
  4: '已拒绝'
}

// 排期状态映射
const scheduleStatusMap = {
  'PENDING': '待执行',
  'RUNNING': '执行中',
  'COMPLETED': '已完成',
  'CANCELLED': '已取消'
}

// 获取详情
const fetchDetails = async () => {
  try {
    loading.value = true
    const res = await getAdvertisementDetail(route.params.id)
    if (res.data.code === 200) {
      adData.value = res.data.data
      // 获取排期数据
      fetchScheduleData()
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  } finally {
    loading.value = false
  }
}

// 获取排期数据
const fetchScheduleData = async () => {
  try {
    scheduleLoading.value = true
    const adId = route.params.id
    const res = await getAdvertisementSchedule(adId)
    
    if (res.data.code === 200) {
      // 直接使用后端返回的数据，包含deviceName
      scheduleData.value = res.data.data || []
    } else {
      console.error('获取排期失败:', res.data.message)
      ElMessage.error(res.data.message || '获取排期数据失败')
    }
  } catch (error) {
    console.error('获取排期数据失败:', error)
    ElMessage.error('获取排期数据失败')
  } finally {
    scheduleLoading.value = false
  }
}

// 状态标签类型
const getStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 待审核
    1: 'success', // 已审核
    2: 'primary', // 投放中
    3: 'success', // 已完成
    4: 'danger'   // 已拒绝
  }
  return typeMap[status] || 'info'
}

// 排期状态标签类型
const getScheduleStatusType = (status) => {
  const typeMap = {
    'PENDING': 'info',
    'RUNNING': 'primary',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return typeMap[status] || 'info'
}

// 时间格式化
const formatTime = (time) => {
  return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '--'
}

onMounted(() => {
  fetchDetails()
})
</script>

<style scoped>
.ad-details-container {
  padding: 20px;
}

.details-card {
  margin-top: 20px;
}

.content-section,
.media-section,
.time-section,
.schedule-section {
  margin-top: 20px;
}

.content-box {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  margin-top: 10px;
  white-space: pre-wrap;
}

.media-content {
  margin-top: 10px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.ad-image {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 4px;
}

.video-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.ad-video {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
}

.no-media {
  color: #909399;
  font-style: italic;
  padding: 30px;
  text-align: center;
}

.schedule-table {
  margin-top: 10px;
}
</style>